//
//  ZRefreshControl.swift
//  下拉刷新
//
//  Created by zero on 17/3/27.
//  Copyright © 2017年 zero. All rights reserved.
//

import UIKit

//  枚举
enum RefreahType: String{
    
    case refreahTypeNomal = "正常"
    case refreahTypePull = "下拉中"
    case refreahTypeRefreah = "刷新中"
}

//  高度
private let refreshControlW: CGFloat = 50

class ZRefreshControl: UIControl {

    //  记录父view
    fileprivate var scrollView:UIScrollView?
    
    //  记录按钮的状态
    var refreahState:RefreahType = .refreahTypeNomal{
        
        didSet{
            
            labContent.text = refreahState.rawValue
            
            if refreahState == .refreahTypeNomal {
                
                imgPullRefresh.transform = CGAffineTransform.identity
                
            }else if refreahState == .refreahTypePull{
                
                imgPullRefresh.transform = CGAffineTransform(rotationAngle: CGFloat(-3 * M_PI))
                
            }else{
                
                UIView.animate(withDuration: 1, animations: {
                    
                    self.scrollView?.contentInset.top += refreshControlW
                    
                }, completion: { (_) in
                    //  打开菊花
                    self.imgActivity.startAnimating()
                    self.imgPullRefresh.isHidden = true
                    
                    //  发送一个通知
                    
                    UIView.animate(withDuration: 1, delay: 1, options: [], animations: {
                        
                        self.scrollView?.contentInset.top -= refreshControlW
                        
                    }, completion: { (_) in
                        
                        //  关闭菊花
                        self.imgActivity.stopAnimating()
                        self.imgPullRefresh.isHidden = false
                        self.sendActions(for: .valueChanged)
                    })
                    
                })
                
                
            }
        }
    }
    
    override init(frame: CGRect) {
        super.init(frame: CGRect(x: 0, y: -refreshControlW, width: UIScreen.main.bounds.size.width, height: refreshControlW))
        //  布局
        setupUI()
        
    }
    
    //  结束菊花
    func endRefreshing() {
        
        refreahState = .refreahTypeNomal
    }
    
    //  布局
    private func setupUI(){
        
        backgroundColor = UIColor.orange
        
        //  添加
        addSubview(labContent)
        
        labContent.translatesAutoresizingMaskIntoConstraints = false
        //  约束
        addConstraint(NSLayoutConstraint(item: labContent, attribute: NSLayoutAttribute.centerX, relatedBy: NSLayoutRelation.equal, toItem: self, attribute: NSLayoutAttribute.centerX, multiplier: 1, constant: 0))
        
        addConstraint(NSLayoutConstraint(item: labContent, attribute: NSLayoutAttribute.centerY, relatedBy: NSLayoutRelation.equal, toItem: self, attribute: NSLayoutAttribute.centerY, multiplier: 1, constant: 0))
        
        //  添加
        addSubview(imgPullRefresh)
        
        imgPullRefresh.translatesAutoresizingMaskIntoConstraints = false
        
        //  约束
        addConstraint(NSLayoutConstraint(item: imgPullRefresh, attribute: NSLayoutAttribute.centerX, relatedBy: NSLayoutRelation.equal, toItem: self, attribute: NSLayoutAttribute.centerX, multiplier: 1, constant: -35))
        
        addConstraint(NSLayoutConstraint(item: imgPullRefresh, attribute: NSLayoutAttribute.centerY, relatedBy: NSLayoutRelation.equal, toItem: self, attribute: NSLayoutAttribute.centerY, multiplier: 1,constant: 0))
        
        //  添加
        addSubview(imgActivity)
        
        imgActivity.translatesAutoresizingMaskIntoConstraints = false
        
        addConstraint(NSLayoutConstraint(item: imgActivity, attribute: NSLayoutAttribute.centerX, relatedBy: NSLayoutRelation.equal, toItem: self, attribute: NSLayoutAttribute.centerX, multiplier: 1, constant: -35))
        addConstraint(NSLayoutConstraint(item: imgActivity, attribute: NSLayoutAttribute.centerY, relatedBy: NSLayoutRelation.equal, toItem: self, attribute: NSLayoutAttribute.centerY, multiplier: 1, constant: 0))
        
        

    }
    
    
    //  懒加载
    private lazy var labContent:UILabel = {
       
        let lab = UILabel()
        
        lab.text = "正常中"
        lab.textColor = UIColor.white
        lab.textAlignment = .center
        lab.font = UIFont.systemFont(ofSize: 14)
        
        return lab
        
    }()
    
    //  tableview_pull_refresh
    private lazy var imgPullRefresh:UIImageView = UIImageView(image: UIImage(named: "tableview_pull_refresh"))
    
    //  刷新的菊花
    private lazy var imgActivity:UIActivityIndicatorView = UIActivityIndicatorView(activityIndicatorStyle: UIActivityIndicatorViewStyle.whiteLarge)
    
    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }

}

extension ZRefreshControl{
    
    //  将要添加到父控件的时候
    override func willMove(toSuperview newSuperview: UIView?) {
        
        //  如果为nil 或者不适合滚动视图 就不同监听
        guard let superView = newSuperview as? UIScrollView else {
            
            return
        }
        
        scrollView = superView
        //  添加kvo观察者
        scrollView?.addObserver(self, forKeyPath: "contentOffset", options: NSKeyValueObservingOptions.new, context: nil)
        
    }
    
    //  观察者模式
    override func observeValue(forKeyPath keyPath: String?, of object: Any?, change: [NSKeyValueChangeKey : Any]?, context: UnsafeMutableRawPointer?) {
        
        
        let contentOffsetMax = -(scrollView!.contentInset.top + refreshControlW)

        let offset = scrollView!.contentOffset.y
        
        
        if scrollView!.isDragging {
            
            //  手指拖动
            if offset > contentOffsetMax && refreahState == .refreahTypePull{
                
                refreahState = .refreahTypeNomal
                
            }else if offset <= contentOffsetMax && refreahState == .refreahTypeNomal{
                refreahState = .refreahTypePull
                
            }

        }else{
            
            //  手指不拖动了
            if refreahState == .refreahTypePull {
                
                refreahState = .refreahTypeRefreah
            }
        }
        
    }
    
}
